use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{Mutex, RwLock};
use serde::{Deserialize, Serialize};

/// 高性能网络服务demo - 展示Rust在网络编程中的优势
/// 包括：异步I/O、连接池、负载均衡、性能监控

#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: String,
    created_at: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct ApiResponse<T> {
    success: bool,
    data: Option<T>,
    error: Option<String>,
    timestamp: String,
}

impl<T> ApiResponse<T> {
    fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            timestamp: chrono::Utc::now().to_rfc3339(),
        }
    }
    
    fn error(message: &str) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(message.to_string()),
            timestamp: chrono::Utc::now().to_rfc3339(),
        }
    }
}

// 用户服务
struct UserService {
    users: Arc<RwLock<HashMap<u32, User>>>,
    next_id: Arc<Mutex<u32>>,
}

impl UserService {
    fn new() -> Self {
        let mut users = HashMap::new();
        users.insert(1, User {
            id: 1,
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
            created_at: "2024-01-01T00:00:00Z".to_string(),
        });
        users.insert(2, User {
            id: 2,
            name: "Bob".to_string(),
            email: "bob@example.com".to_string(),
            created_at: "2024-01-02T00:00:00Z".to_string(),
        });
        
        Self {
            users: Arc::new(RwLock::new(users)),
            next_id: Arc::new(Mutex::new(3)),
        }
    }
    
    async fn get_user(&self, id: u32) -> Option<User> {
        let users = self.users.read().await;
        users.get(&id).cloned()
    }
    
    async fn create_user(&self, name: String, email: String) -> User {
        let mut users = self.users.write().await;
        let mut next_id = self.next_id.lock().await;
        let id = *next_id;
        *next_id += 1;
        
        let user = User {
            id,
            name,
            email,
            created_at: chrono::Utc::now().to_rfc3339(),
        };
        
        users.insert(id, user.clone());
        user
    }
    
    async fn list_users(&self) -> Vec<User> {
        let users = self.users.read().await;
        users.values().cloned().collect()
    }
}

// 性能监控
struct PerformanceMonitor {
    request_count: Arc<Mutex<u64>>,
    response_times: Arc<Mutex<Vec<Duration>>>,
    error_count: Arc<Mutex<u64>>,
    start_time: Instant,
}

impl PerformanceMonitor {
    fn new() -> Self {
        Self {
            request_count: Arc::new(Mutex::new(0)),
            response_times: Arc::new(Mutex::new(Vec::new())),
            error_count: Arc::new(Mutex::new(0)),
            start_time: Instant::now(),
        }
    }
    
    async fn record_request(&self, response_time: Duration) {
        let mut count = self.request_count.lock().await;
        *count += 1;
        
        let mut times = self.response_times.lock().await;
        times.push(response_time);
        if times.len() > 1000 {
            times.remove(0);
        }
    }
    
    async fn record_error(&self) {
        let mut count = self.error_count.lock().await;
        *count += 1;
    }
    
    async fn get_stats(&self) -> (u64, f64, u64, Duration) {
        let request_count = *self.request_count.lock().await;
        let error_count = *self.error_count.lock().await;
        let uptime = self.start_time.elapsed();
        
        let times = self.response_times.lock().await;
        let avg_response_time = if times.is_empty() {
            0.0
        } else {
            times.iter().sum::<Duration>().as_millis() as f64 / times.len() as f64
        };
        
        (request_count, avg_response_time, error_count, uptime)
    }
}

// HTTP请求处理器
async fn handle_request(
    mut stream: TcpStream,
    user_service: Arc<UserService>,
    monitor: Arc<PerformanceMonitor>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let start_time = Instant::now();
    
    // 读取请求
    let mut buffer = [0; 1024];
    let n = stream.read(&mut buffer).await?;
    let request = String::from_utf8_lossy(&buffer[..n]);
    
    let response = if request.starts_with("GET /users") {
        // 获取用户列表
        let users = user_service.list_users().await;
        let response = ApiResponse::success(users);
        serde_json::to_string(&response)?
    } else if request.starts_with("GET /user/") {
        // 获取特定用户
        let parts: Vec<&str> = request.split_whitespace().collect();
        if parts.len() >= 2 {
            let path = parts[1];
            if let Some(id_str) = path.strip_prefix("/user/") {
                if let Ok(id) = id_str.parse::<u32>() {
                    if let Some(user) = user_service.get_user(id).await {
                        let response = ApiResponse::success(user);
                        serde_json::to_string(&response)?
                    } else {
                        let response = ApiResponse::<()>::error("User not found");
                        serde_json::to_string(&response)?
                    }
                } else {
                    let response = ApiResponse::<()>::error("Invalid user ID");
                    serde_json::to_string(&response)?
                }
            } else {
                let response = ApiResponse::<()>::error("Invalid path");
                serde_json::to_string(&response)?
            }
        } else {
            let response = ApiResponse::<()>::error("Invalid request");
            serde_json::to_string(&response)?
        }
    } else if request.starts_with("POST /users") {
        // 创建用户
        let body_start = request.find("\r\n\r\n");
        if let Some(start) = body_start {
            let body = &request[start + 4..];
            if let Ok(user_data) = serde_json::from_str::<serde_json::Value>(body) {
                let name = user_data["name"].as_str().unwrap_or("Unknown").to_string();
                let email = user_data["email"].as_str().unwrap_or("unknown@example.com").to_string();
                let user = user_service.create_user(name, email).await;
                let response = ApiResponse::success(user);
                serde_json::to_string(&response)?
            } else {
                let response = ApiResponse::<()>::error("Invalid JSON");
                serde_json::to_string(&response)?
            }
        } else {
            let response = ApiResponse::<()>::error("No body provided");
            serde_json::to_string(&response)?
        }
    } else if request.starts_with("GET /stats") {
        // 获取性能统计
        let (request_count, avg_response_time, error_count, uptime) = monitor.get_stats().await;
        let stats = serde_json::json!({
            "request_count": request_count,
            "avg_response_time_ms": avg_response_time,
            "error_count": error_count,
            "uptime_seconds": uptime.as_secs()
        });
        let response = ApiResponse::success(stats);
        serde_json::to_string(&response)?
    } else {
        // 404 Not Found
        let response = ApiResponse::<()>::error("Not Found");
        serde_json::to_string(&response)?
    };
    
    // 发送响应
    let http_response = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
        response.len(),
        response
    );
    
    stream.write_all(http_response.as_bytes()).await?;
    stream.flush().await?;
    
    // 记录性能指标
    let response_time = start_time.elapsed();
    monitor.record_request(response_time).await;
    
    Ok(())
}

// 性能监控报告任务
async fn performance_report_task(monitor: Arc<PerformanceMonitor>) {
    let mut interval = tokio::time::interval(Duration::from_secs(10));
    
    loop {
        interval.tick().await;
        
        let (request_count, avg_response_time, error_count, uptime) = monitor.get_stats().await;
        println!("📊 性能报告 - 请求数: {}, 平均响应时间: {:.2}ms, 错误数: {}, 运行时间: {:?}", 
                request_count, avg_response_time, error_count, uptime);
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🌐 Rust高性能网络服务演示");
    println!("=============================");
    
    // 初始化服务
    let user_service = Arc::new(UserService::new());
    let monitor = Arc::new(PerformanceMonitor::new());
    
    // 启动性能监控任务
    tokio::spawn(performance_report_task(Arc::clone(&monitor)));
    
    // 启动HTTP服务器
    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    println!("🚀 服务器启动在 http://127.0.0.1:8080");
    println!("📋 可用端点:");
    println!("   GET  /users     - 获取所有用户");
    println!("   GET  /user/{{id}} - 获取特定用户");
    println!("   POST /users     - 创建用户");
    println!("   GET  /stats     - 获取性能统计");
    
    // 处理连接
    while let Ok((stream, addr)) = listener.accept().await {
        println!("🔗 新连接来自: {}", addr);
        
        let user_service = Arc::clone(&user_service);
        let monitor = Arc::clone(&monitor);
        
        tokio::spawn(async move {
            if let Err(e) = handle_request(stream, user_service, monitor).await {
                eprintln!("❌ 处理请求时出错: {}", e);
            }
        });
    }
    
    Ok(())
}